<template>
  <el-dialog :title="title" v-model="visible" append-to-body :lock-scroll="true" center
    custom-class="RegularPop dataSource" :close-on-click-modal="false" @close="modalClose">
    <el-form :model="form" :rules="rules" ref="ruleFormRef" :inline="true">
      <h1>基础信息</h1>
      <el-row>
        <el-col>
          <el-form-item label="经营地址" required class="config-code">
            <areaItem @outValue="getAreaCode" ref="areaClear" :areaCode="areaCode" :isDisabled="readOnly"></areaItem>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="主键Id" prop="ident">
            <el-input v-model="form.ident" placeholder="主键Id" clearable @focus="handhide" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="页面标题" prop="title">
            <el-input v-model="form.title" placeholder="页面标题" clearable @focus="handhide" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="显示模式" prop="showMode">
            <el-select v-model="form.showMode" placeholder="选择显示模式" clearable @focus="handhide">
              <el-option v-for="dict in v_show_mode" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="显示模式项">
            <div class="modeList" :class="{ 'isActive': selectShow }">
              <div class="show-mode-select" @click.stop='handleClick()'>
                <span v-for="item in modeName" :key="item"> {{ item.title }}</span>
              </div>
              <ul v-show="selectShow">
                <li v-for="(item, index) in ModeItemList" :key="index" @click="changeModeLi(item, index)"
                  :class="listSelect.indexOf(item) == '-1' ? ' ' : 'select'">
                  <span> {{ item.title }}</span>
                  <input v-model="item.param" placeholder="输入参数" clearable class="params" />
                </li>
              </ul>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="场景设施">

            <div class="modeList" :class="{ 'isActive': sceneShow }">
              <div class="show-mode-select" @click.stop='handleClick2()'>
                <span v-for="item in senceName" :key="item" :title="item"> {{ item.title }}</span>
              </div>
              <ul v-show="sceneShow" class="sceneUL">
                <li v-for="(item, index) in sceneItemList" :key="index" @click="changeSceneLi(item, index)"
                  :class="sceneSelect.indexOf(item) == '-1' ? ' ' : 'select'">
                  <div class="item-title">
                    <span>{{ (index + 1) }}. {{ item.title }}</span>
                    <span> {{ item.ident }}</span>
                  </div>

                  <input v-model="item.api" placeholder="输入数据接口" clearable class="params" />
                  <input v-model="item.detailApi" placeholder="详情接口" clearable class="params" />
                  <el-col :span="12">
                    <el-form-item label="类型">
                      <el-select v-model="item.type" placeholder="选择类型" clearable>
                        <el-option v-for="dict in she_shi_type" :key="dict.value" :label="dict.label"
                          :value="dict.value" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="显示模式">
                      <el-select v-model="item.showMode" placeholder="选择类型" clearable>
                        <el-option v-for="dict in xian_shi_mode" :key="dict.value" :label="dict.label"
                          :value="dict.value" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="弹窗组件" class="componentName">
                      <input v-model="item.componentName" placeholder="弹窗组件" clearable />
                    </el-form-item>
                  </el-col>
                </li>
              </ul>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="租户" prop="tenantId">
            <el-select v-model="form.tenantId" filterable placeholder="选择租户" @change="tenantChange">
              <el-option v-for="(item, index) in tenantList" :key="index" :label="item" :value="index" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="背景image">
            <el-input v-model="form.image" placeholder="背景image" clearable @focus="handhide" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="背景标题">
            <el-input v-model="form.text" placeholder="背景标题" clearable @focus="handhide" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel">返回</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import areaItem from "@/views/areaItem";
import {
  getFacilitiesDic,
  addPageConfig,
  updatePageConfig,
} from "@/api/screen/facilities";
import { getTenantDic } from '@/api/tenant/tenant'
const { proxy } = getCurrentInstance();
const { v_show_mode, xian_shi_mode, she_shi_type } = proxy.useDict("v_show_mode", "xian_shi_mode", 'she_shi_type');
const title = ref("");
const visible = ref(false);
const tenantList = ref({});
const tenant = ref("")
const readOnly = ref(false)
const data = reactive({
  form: {
    image: undefined,
    text: undefined,
  },
  sceneItemList: [],
  ModeItemList: [],
  rules: {
    ident: [{ required: true, message: "请输入id标识", trigger: "blur" }],
    title: [{ required: true, message: "请输入标题", trigger: "blur" }],
    showMode: [{ required: true, message: "请选择", trigger: "change" }],
    tenantId: [{ required: true, message: "租户不能为空", trigger: "blur" }],
  },
  modeName: [],
  selectShow: false,//场景模式
  listSelect: [], //设置第二个数组存选中的元素
  select: -1,//设置选中状态
  selectItem: [],
  sceneShow: false,//场景设施显示下拉
  senceName: [],
  sceneSelect: [],
  type: undefined
});

const { form, rules, sceneItemList, modeName, selectShow, listSelect,
  select, selectItem, ModeItemList, sceneShow, senceName, sceneSelect, type } = toRefs(data);
const areaCode = ref('')
function getAreaCode(code) {
  console.log('outputvale', code)
  form.value.areaCode = code;
  //   tempCode.value = code
}
getTenantDic(tenant.value).then(res => {
  if (res.code == 200) {
    tenantList.value = res.data
  }

})
function tenantChange(val) {
  form.value.tenantId = val
}
function modeX() {
  // console.log('v_show_mode',v_show_mode._object.v_show_mode)
  let mode = v_show_mode._object.v_show_mode
  let newarr = [];
  for (let i in mode) {
    let object = { value: '', title: '', param: '' }
    newarr.push(object)
    newarr[i].value = mode[i].value
    newarr[i].title = mode[i].label
  }
  ModeItemList.value = newarr;
}

function handhide() {
  if (selectShow.value == true) {
    selectShow.value = false
  }
  if (sceneShow.value == true) {
    sceneShow.value = false
  }

}
getFacilitiesDic().then((res) => {
  if (res.code == 200) {
    let newarr = [];
    for (let i in res.data) {
      let object = { id: '', title: '', ident: '', api: '', detailApi: '', type: '', showMode: '', componentName: '' }
      newarr.push(object)
      newarr[i].id = res.data[i].value;
      newarr[i].title = res.data[i].label;
      // newarr[i].type = res.data[i].type
      // newarr[i].showMode = res.data[i].showMode
      // newarr[i].componentName = res.data[i].componentName
    }

    sceneItemList.value = newarr
  }
});

/** 重置操作表单 */
function reset() {
  form.value = {};
  areaCode.value = ''
  proxy.resetForm("ruleFormRef");
}
// 显示弹框
function add() {
  visible.value = true;
  title.value = "新增可视化页面配置";
  type.value = 1
  readOnly.value = false
  reset();
  modeX();
  getFacilitiesDic()
}
const edit = (row) => {
  reset();
  console.log("修改", row);
  visible.value = true;
  type.value = 2
  readOnly.value = false
  title.value = "修改可视化页面配置";
  modeX();
  getFacilitiesDic()
  form.value = Object.assign({}, row);
  form.value.showMode = form.value.showMode + '';
  form.value.tenantId = form.value.tenantId + '';
  form.value.sceneFacilities = JSON.parse(form.value.sceneFacilities)
  form.value.showModeItem = JSON.parse(form.value.showModeItem)
  areaCode.value = row.areaCode;
  // console.log('form.value.sceneFacilities', form.value.sceneFacilities)
  // console.log('form.value.showModeItem ',)
  modeName.value = form.value.showModeItem
  // ModeItemList.value = JSON.parse(form.value.showModeItem)
  senceName.value = form.value.sceneFacilities
  // sceneItemList.value = form.value.sceneFacilities
  for (let index in ModeItemList.value) {
    for (let k in form.value.showModeItem) {
      if (ModeItemList.value[index].title == form.value.showModeItem[k].title) {
        ModeItemList.value[index].param = form.value.showModeItem[k].param
      }
    }
  }
  for (let i in sceneItemList.value) {//设施
    //  console.log('sceneItemList.value.id', sceneItemList.value[i].id)
    for (let j in form.value.sceneFacilities) {
      //   console.log('form.value.sceneFacilities[j].id', form.value.sceneFacilities[j].id)
      if (sceneItemList.value[i].id == form.value.sceneFacilities[j].id) {
        sceneItemList.value[i] = form.value.sceneFacilities[j]
        sceneItemList.value[i].api = form.value.sceneFacilities[j].api
        sceneItemList.value[i].detailApi = form.value.sceneFacilities[j].detailApi
        sceneItemList.value[i].type = form.value.sceneFacilities[j].type + ''
        sceneItemList.value[i].showMode = form.value.sceneFacilities[j].showMode + ''
        sceneItemList.value[i].componentName = form.value.sceneFacilities[j].componentName
      }
    }
  }
};
/** 取消按钮 */
function modalClose() {
  reset();
  proxy.$refs.areaClear.clearValue()
  visible.value = false;
}
/** 取消按钮 */
function cancel() {
  reset();
  visible.value = false;
}
function selectTrigger(val) {
  console.log("valvalvalvalval", val);
}
function handleClick() {
  sceneShow.value = false
  selectShow.value = !selectShow.value;

}
function handleClick2() {
  selectShow.value = false;
  sceneShow.value = !sceneShow.value;
}

function changeModeLi(item, index) {
  console.log('item', item)
  selectItem.value = item
  let id = listSelect.value.indexOf(selectItem.value)
  if (id == -1) { //新数组中没有这个元素，点击的时候修改样式，并将元素添加进去
    listSelect.value.push(selectItem.value);
    console.log('listSelect.value', listSelect.value)
    select.value = index
  } else {//新数组中有这个元素，点击的时候选中样式消失，元素推出
    listSelect.value.pop(selectItem.value)
    select.value = -1
  }
  form.value.showModeItem = listSelect.value
  console.log('form.value.showModeItem', form.value.showModeItem)
  // let selItem = []
  // for (let i in form.value.showModeItem) {
  //   selItem.push(form.value.showModeItem[i].title)
  // }
  modeName.value = form.value.showModeItem;

}
function changeSceneLi(item, index) {
  selectItem.value = item
  let id = sceneSelect.value.indexOf(selectItem.value)
  if (id == -1) { //新数组中没有这个元素，点击的时候修改样式，并将元素添加进去
    sceneSelect.value.push(selectItem.value);
    console.log('sceneSelect.value', sceneSelect.value)
    select.value = index
  } else {//新数组中有这个元素，点击的时候选中样式消失，元素推出
    sceneSelect.value.pop(selectItem.value)
    select.value = -1
  }
  form.value.sceneFacilities = sceneSelect.value
  // let selItem = []
  // for (let i in form.value.sceneFacilities) {
  //   selItem.push(form.value.sceneFacilities[i].title)
  // }
  senceName.value = form.value.sceneFacilities
}

function submitForm() {
  proxy.$refs["ruleFormRef"].validate((valid) => {
    if (valid) {
      let imgObject = { image: form.value.image, text: form.value.text }
      form.value.background = JSON.stringify(imgObject);
      form.value.showModeItem = JSON.stringify(form.value.showModeItem)
      form.value.sceneFacilities = JSON.stringify(form.value.sceneFacilities)
      if (type.value == 2) {
        updatePageConfig(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          visible.value = false;
          proxy.$emit('refresh')
        }).catch(err => {
          console.log('err', err)
        })
      } else {
        addPageConfig(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          visible.value = false;
          proxy.$emit('refresh')
        }).catch(err => {
          console.log('err', err)
        })

      }
    } else {
      proxy.$modal.msgError("提交失败！");
      return false;
    }
  });
}
defineExpose({
  add,
  edit,
});
</script>
<style lang="scss">
.modeList {
  background: #eff0f1;
  width: 98%;
  height: 35px;
  border-radius: 4px;
  position: relative;
  padding: 0 4%;

  &:after {
    content: "";
    font-size: 14px;
    color: #666;
    background: url("../../../../assets/images/manage/xiala.png") no-repeat;
    background-size: 100%;
    width: 14px;
    height: 8px;
    transform: rotateZ(0deg);
    position: relative;
    top: 14px;
    right: 4%;
    display: block;
    position: absolute;
  }

  ul {
    position: absolute;
    z-index: 2;
    background: #fff;
    width: 100%;
    left: 0;
    border: 1px solid #eff0f1;
    box-shadow: 0 0 5px #eff0f1;
    top: 43px;
    border-radius: 4px;
    z-index: 22;

    li {
      width: 95%;
      line-height: 50px;
      margin: 0 auto;
      display: flex;
      justify-content: space-between;
      align-items: center;

      input.params {
        margin-left: 3%;
        width: 68%;
        height: 34px;
        background: #ffffff;
        border: 1px solid #fff;
        border-radius: 4px;
        padding: 0 2%;
      }
    }

    li.select {

      line-height: 50px;

      span {
        color: #0099ff !important;
      }

      input.params {
        height: 34px;
        border: 1px solid #0099ff;
      }
    }
  }

  ul.sceneUL {
    width: 313%;
    height: 240px;
    left: -55%;
    overflow-y: scroll;

    li {
      display: block;
      border-bottom: 1px solid #dadada;
      padding-bottom: 1%;

      span {
        display: block;
        float: left;
        width: max-content;
      }

      &:after {
        content: "";
        clear: both;
        display: block;
      }

      input.params {
        width: 42%;
        padding: 0 1%;
        border: 1px solid #dadada;
      }

      .componentName {
        input {
          width: 300px;
          border: 0;
          background: #eff0f1;
          line-height: 35px;
          border-radius: 4px;
          padding: 0 4%;
          color: #666;
        }
      }

      i.el-icon.el-select__caret.el-select__icon {
        top: 1px !important;
      }
    }
  }
}

.show-mode-select {
  width: 78%;
  display: flex;
  align-items: center;
  height: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  white-space: nowrap;

  span {
    display: block;
    width: max-content;
    padding: 0 1%;

    &:after {
      content: ",";
      display: inline-block;
      color: #333;
      font-size: 16px;
    }
  }

  span:last-child {
    &:after {
      content: "";
      color: #f00;
      display: none;
    }
  }
}

.el-form-item.config-code .el-form-item__content {
  .el-select {
    margin-bottom: 18px;
  }

  .el-select:last-child {
    margin-bottom: 0px;
  }
}
</style>